package com.genius.service.impl;

import com.genius.enums.ResponseType;
import com.genius.exception.GraceException;
import com.genius.mapper.DictMapper;
import com.genius.service.DictService;
import com.genius.system.pojo.Dict;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Override
    public Dict selectDictById(Long dictId) {
        return dictMapper.selectDictById(dictId);
    }

    @Override
    public List<Dict> selectDictByPage(Dict dictType) {
        return dictMapper.selectDictByPage(dictType);
    }

    @Override
    @Transactional
    public int insertDict(Dict dict) {

        checkDictIsExist(dict);
        return dictMapper.insertDict(dict);
    }

    @Override
    @Transactional
    public int updateDict(Dict dict) {
        checkDictIsExist(dict);
        return dictMapper.updateDict(dict);
    }

    @Override
    @Transactional
    public int deleteDictByIds(Long[] ids) {

        if (dictMapper.dictCanDeleteOrNot(ids)) {
            GraceException.display(ResponseType.ASSOCIATION_EXIST_ERROR);
        }
        return dictMapper.deleteDictByIds(ids);
    }

    /**
     * 检查字典是否已存在
     * @param dict 字典信息
     */
    private void checkDictIsExist(Dict dict){
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("dictType",dict.getDictType());
        hashMap.put("dictId",dict.getDictId());
        if (!dictMapper.selectDictIsExistByDict(hashMap)) {
            GraceException.display(ResponseType.DICT_TYPE_EXIST_ERROR);
        }
    }
}
